// src/composables/useCheckout.js
import { ref, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

export const useCheckout = () => {
  const router = useRouter();
  const totalPrice = ref(0);

  // 获取当前登录用户
  const getCurrentUser = () => localStorage.getItem("currentUser");

  // 结算核心逻辑
  const handleCheckout = async (productsToBuy, redirect = true) => {
    if (!localStorage.getItem("isLoggedIn")) {
      throw new Error("请先登录");
    }

    if (!productsToBuy || productsToBuy.length === 0) {
      throw new Error("请选择商品");
    }

    try {
      // 1. 批量校验并更新库存
      await Promise.all(
        productsToBuy.map(async (product) => {
          const productId = product.id || product.productId;
          const deductQuantity = product.quantity || 1;

          // 获取当前库存
          const stockRes = await axios.get(`http://localhost:3000/products/${productId}`);
          const currentStock = stockRes.data.stock_quantity;
          
          if (currentStock < deductQuantity) {
            throw new Error(`【${product.name}】库存不足（剩余 ${currentStock} 件，需购买 ${deductQuantity} 件）`);
          }

          // 更新库存
          await axios.patch(`http://localhost:3000/products/${productId}`, {
            stock_quantity: currentStock - deductQuantity
          });
        })
      );

      // 2. 创建订单
      const orderData = {
        id: `ORD${Date.now()}`,
        userId: getCurrentUser(),
        createdAt: new Date().toISOString(),
        status: "待接单",
        products: productsToBuy.map(product => ({
          productId: product.id || product.productId,
          name: product.name,
          price: product.price,
          quantity: product.quantity || 1,
          image_url: product.image_url,
          shopName: product.shopName || "默认商家"
        })),
        totalPrice: productsToBuy.reduce((sum, p) => sum + (p.price * (p.quantity || 1)), 0)
      };

      totalPrice.value = orderData.totalPrice;

      // 3. 发送订单到后端
      const orderResponse = await axios.post('http://localhost:3000/orders', orderData);
      console.log('订单创建成功:', orderResponse.data);

      // 4. 清空购物车中已结算的商品（如果是从购物车结算）
      if (redirect) {
        router.push('/main/profile/user-center/orders');
      }

      return orderData;
    } catch (error) {
      console.error("结算失败:", error);
      throw error;
    }
  };

  return {
    handleCheckout,
    totalPrice
  };
};